import React, {useState, useEffect} from 'react'
import { Form, Input } from 'antd'
import { RmbIcon, PercentIcon, DateIcon } from '@components/icon/system'
import classnames from 'classnames'

const rules = {
  amount: [
    {
      required: true,
      message: '请输入贷款金额'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入贷款金额必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ],
  interest: [
    {
      required: true,
      message: '请输入年利率'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入年利率必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ],
  month: [
    {
      required: true,
      message: '请输入贷款期数'
    },
    {
      validator: (_, value) => {
        if (value === 0 || value === '0') {
          return Promise.reject(new Error('输入贷款期数比例必须大于0'));
        }
        return Promise.resolve();
      },
    }
  ]
}

const LoansForm = (props) => {
  const [repayment, setRepayment] = useState('equalInstallment')
  const [repaymentOption] = useState([
    {
      value: 'equalInstallment',
      label: '等额本息',
    },
    {
      value: 'equalPrincipal',
      label: '等额本金',
    },{
      value: 'equalPrincipalInterest',
      label: '等本等息',
    }
  ])

  useEffect(() => {
  }, [])

  const handleSubmit = (values) => {
    const formData = {
      ...values,
      amount: Number(values.amount),
      month: Number(values.month)
    };
    const { amount, interest, month, repayment } = formData

    const monthlyInterestRate = interest / 100 / 12;

    let monthlyPayment = 0;
    let totalPayment = 0;
    let totalInterest = 0;
    let paymentSchedule = [];
    let remainingBalance = amount;

    if (repayment === 'equalInstallment') {
        // 等额本息
        monthlyPayment = (amount * monthlyInterestRate) / (1 - Math.pow(1 + monthlyInterestRate, -month));
        totalPayment = monthlyPayment * month;
        totalInterest = totalPayment - amount;

        for (let i = 1; i <= month; i++) {
            const interestPayment = remainingBalance * monthlyInterestRate;
            const principalPayment = monthlyPayment - interestPayment;
            remainingBalance -= principalPayment;

            if (remainingBalance < 0) remainingBalance = 0;

            paymentSchedule.push({
                month: i,
                payment: monthlyPayment.toFixed(2),
                principal: principalPayment.toFixed(2),
                interest: interestPayment.toFixed(2),
                endingBalance: remainingBalance.toFixed(2)
            })
        }
    } else if (repayment === 'equalPrincipal') {
        // 等额本金
        const principalPayment = amount / month;
        totalInterest = 0;

        for (let i = 1; i <= month; i++) {
            const interestPayment = remainingBalance * monthlyInterestRate;
            monthlyPayment = principalPayment + interestPayment;
            remainingBalance -= principalPayment;
            totalInterest += interestPayment;

            if (remainingBalance < 0) remainingBalance = 0;

            paymentSchedule.push({
              month: i,
              payment: monthlyPayment.toFixed(2),
              principal: principalPayment.toFixed(2),
              interest: interestPayment.toFixed(2),
              endingBalance: remainingBalance.toFixed(2)
            })
        }

        totalPayment = amount + totalInterest;
    } else {
        // 等本等息
        const principalPayment = amount / month;
        const interestPayment = amount * monthlyInterestRate;
        monthlyPayment = principalPayment + interestPayment;
        totalInterest = interestPayment * month;
        totalPayment = amount + totalInterest;

        for (let i = 1; i <= month; i++) {
            remainingBalance -= principalPayment;

            if (remainingBalance < 0) remainingBalance = 0;

            paymentSchedule.push({
              month: i,
              payment: monthlyPayment.toFixed(2),
              principal: principalPayment.toFixed(2),
              interest: interestPayment.toFixed(2),
              endingBalance: remainingBalance.toFixed(2)
            })
        }
    }

    props.onSubmit && props.onSubmit({
      monthlyPayment: Number(monthlyPayment).toFixed(2),
      totalPayment: Number(totalPayment).toFixed(2),
      totalInterest: Number(totalInterest).toFixed(2),
      remainingBalance: Number(remainingBalance).toFixed(2),
      paymentSchedule
    })
  }

  return (
    <div className="form-item">
      <Form
        name="loans-form"
        form={props.form}
        labelCol={{ span: 24 }}
        wrapperCol={{ span: 24 }}
        colon={false}
        onFinish={handleSubmit}
        initialValues={{
          repayment: 'equalInstallment',
          interest: 10,
          month: 12
        }}
      >
        <Form.Item label="贷款金额(元)" name="amount" rules={rules.amount}>
          <Input placeholder="0" prefix={<RmbIcon width={14} height={14} fill="#999" />} />
        </Form.Item>
        <Form.Item label="年利率" name="interest" rules={rules.interest}>
          <Input placeholder="请输入贷款金额" suffix={<PercentIcon width={14} height={14} fill="#999" />} />
        </Form.Item>
        <Form.Item label="贷款期数(月)" name="month" rules={[{ required: true }]}>
          <Input placeholder="请输入贷款期数" prefix={<DateIcon width={14} height={14} fill="#999" />} />
        </Form.Item>
        <Form.Item label="还款方式" name="repayment">
          <ul className="repayment-select" name="repayment">
            {repaymentOption.map((item) => (
              <li
                key={item.value}
                onClick={(e) => {
                  setRepayment(item.value)
                  props.form.setFieldValue('repayment', item.value)
                }}
                className={classnames({
                  active: item.value === repayment
                })}
              >
                {item.label}
              </li>
            ))}
          </ul>
        </Form.Item>
      </Form>
    </div>
  )
}

export default LoansForm;